package org.dreamfly.dreamalarm;

import java.util.Calendar;

import org.dreamfly.dreamalarm.bean.Alarm;
import org.dreamfly.dreamalarm.util.DreamAlarmDateFormat;
import org.dreamfly.dreamalarm.widget.AlarmRingPreference;
import org.dreamfly.dreamalarm.widget.DreamAlarmEditTextPreference;
import org.dreamfly.dreamalarm.widget.DreamAlarmListPreference;
import org.dreamfly.dreamalarm.widget.IntervalLongListPreference;
import org.dreamfly.dreamalarm.widget.MethodListPreference;
import org.dreamfly.dreamalarm.widget.RepeatMutiSelectListPreference;

import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import android.text.format.DateFormat;
import android.view.KeyEvent;
import android.widget.TimePicker;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;

public class NewOrModifyAlarmActivity extends PreferenceActivity implements OnPreferenceChangeListener{

	Alarm alarm;
	boolean isAdd=true;
	private boolean turnChanged=false; 
	private int stateInit=-1;
	
	boolean sleepRing=true;
	
	private final String entries_empty_value="";
	
	private CheckBoxPreference turnOnPreference;
	private Preference timePreference;
	private RepeatMutiSelectListPreference repeatPreference;
	private DreamAlarmEditTextPreference tagPreference;
	private DreamAlarmListPreference typePreference;
	
	private AlarmRingPreference ringPreference;
	private String systemRingSource="content://settings/system/ringtone";
	
	private IntervalLongListPreference intervalLongPreference;
	private MethodListPreference closeMethodPreference;
	private Preference startWorkTimePreference;
	
	private final int DIALOG_TIMEPICKER_TIME=0;
	private final int DIALOG_TIMEPICKER_STARTWORKTIME=1;
	
	//tow time back to cancel input
    private Calendar haveCheckedKeyBack=Calendar.getInstance();
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MobclickAgent.onError(this);
		addPreferencesFromResource(R.xml.newalarm_preference);
		
		iniComponent();	
		
		haveCheckedKeyBack.setTimeInMillis(System.currentTimeMillis()-5*1000);
	}
	
	private void iniComponent(){
		//初始化各个部件
		turnOnPreference=(CheckBoxPreference)findPreference("turnon");
		timePreference=findPreference("time");
		
		repeatPreference=(RepeatMutiSelectListPreference)findPreference("repeat");
		repeatPreference.setValue(entries_empty_value);
		
		tagPreference=(DreamAlarmEditTextPreference)findPreference("tag");
		tagPreference.setText("");
		
		typePreference=(DreamAlarmListPreference)findPreference("type");
		typePreference.setValue(typePreference.getEntryValues()[0].toString());
		typePreference.setOnPreferenceChangeListener(this);
		
		ringPreference=(AlarmRingPreference)findPreference("ring");	
		ringPreference.setValue(systemRingSource);
		
		intervalLongPreference=(IntervalLongListPreference)findPreference("interval");
		intervalLongPreference.setValue(intervalLongPreference.getEntryValues()[intervalLongPreference.getEntryValues().length-1].toString());
		
		closeMethodPreference=(MethodListPreference)findPreference("close_method");
		closeMethodPreference.setValue(closeMethodPreference.getEntryValues()[0].toString());
		
		startWorkTimePreference=findPreference("worktime");
		
		alarm=new Alarm();
		alarm.setTime(Calendar.getInstance());
		
		//查看方法 如果是修改初始化各部件属性
		Intent intent=this.getIntent();
		isAdd=intent.getExtras().getString(Constants.KEY_BETWEEN_ACTIVITY_METHOD)
		            .equals(Constants.KEY_BETWEEN_ACTIVITY_METHOD_ADD);
		if(!isAdd){
			iniComponentUpdate(intent);
		}else{
			//add
			turnOnPreference.setChecked(true);
		}	
		
		//当是提醒类型时，需要先修改界面
		if(alarm.getType()==Alarm.TYPE_NOTIFY){
			((PreferenceCategory) findPreference("close_setting")).removePreference(startWorkTimePreference);
			((PreferenceCategory) findPreference("sound_setting")).removePreference(ringPreference);
		}
	}
	
	private void iniComponentUpdate(Intent intent){
		alarm=(Alarm)intent.getExtras().getSerializable(Constants.KEY_BETWEEN_ACTIVITY_ALARM);
		
		if(alarm.getState()==Alarm.TURN_ON){
			turnOnPreference.setChecked(true);
		}else{
			turnOnPreference.setChecked(false);
		}
		stateInit=alarm.getState();
		
		timePreference.setSummary(alarm.getTimeView());
		
		repeatPreference.initChoose(alarm.getRepeat());
		
		if(!alarm.getTag().equals("")){
			tagPreference.setText(alarm.getTag());
		}
		
		if(alarm.getType()==Alarm.TYPE_NOTIFY){
			typePreference.setValue(typePreference.getEntryValues()[1].toString());
		}
		
		if(alarm.getType()==Alarm.TYPE_GETUP){
			ringPreference.setValue(alarm.getRingSource());
			startWorkTimePreference.setSummary(alarm.getWorkTime());
		}
		
		
		switch(alarm.getReringInterval()){
			case Alarm.INTERVAL_LONG_1:
				intervalLongPreference.setValue(intervalLongPreference.getEntryValues()[0].toString());
				break;
			case Alarm.INTERVAL_LONG_2:
				intervalLongPreference.setValue(intervalLongPreference.getEntryValues()[1].toString());
				break;
			case Alarm.INTERVAL_LONG_3:
				intervalLongPreference.setValue(intervalLongPreference.getEntryValues()[2].toString());
				break;
			case Alarm.INTERVAL_LONG_4:
				intervalLongPreference.setValue(intervalLongPreference.getEntryValues()[3].toString());
				break;
			case Alarm.INTERVAL_LONG_5:
				intervalLongPreference.setValue(intervalLongPreference.getEntryValues()[4].toString());
				break;
			case Alarm.INTERVAL_LONG_6:
				intervalLongPreference.setValue(intervalLongPreference.getEntryValues()[5].toString());
				break;
			case Alarm.INTERVAL_LONG_7:
				intervalLongPreference.setValue(intervalLongPreference.getEntryValues()[6].toString());
				break;
		}
		
		if(alarm.getEndType()==Alarm.Handle_SHOCK){
			closeMethodPreference.setValue(closeMethodPreference.getEntryValues()[1].toString());
		}
	}
	
	// --------------------------------------------------------------------
	// PreferenceActivity相关继承及tools
	
	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		// TODO Auto-generated method stub
		if(typePreference==preference){
			if(newValue.equals(typePreference.getEntryValues()[0].toString())){
				((PreferenceCategory) findPreference("close_setting")).addPreference(startWorkTimePreference);
				((PreferenceCategory) findPreference("sound_setting")).addPreference(ringPreference);
			}else{
				((PreferenceCategory) findPreference("close_setting")).removePreference(startWorkTimePreference);
				((PreferenceCategory) findPreference("sound_setting")).removePreference(ringPreference);
			}
			return true;
		}
		return false;
	} 
	
	@Override
    protected Dialog onCreateDialog(int id) {
        Dialog d;
        
        int hour=0,minute=0;
        switch (id) {
        case DIALOG_TIMEPICKER_TIME:
        	if(alarm.getTimeDate()!=null){
        		hour=alarm.getTimeDate().get(Calendar.HOUR_OF_DAY);
        		minute=alarm.getTimeDate().get(Calendar.MINUTE);
    		}else{
    			hour=Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
    			minute=Calendar.getInstance().get(Calendar.MINUTE);
    		}
            d = new TimePickerDialog(NewOrModifyAlarmActivity.this,
            		new TimePickerDialog.OnTimeSetListener(){

						@Override
						public void onTimeSet(TimePicker view, int hourOfDay,
								int minute) {
							// TODO Auto-generated method stub
							timePreference.setSummary(DreamAlarmDateFormat.formatTime(hourOfDay,minute));
						}},
						hour, minute, DateFormat.is24HourFormat(NewOrModifyAlarmActivity.this));
            d.setTitle(getResources().getString(R.string.time_dialog_title));
            break;
        case DIALOG_TIMEPICKER_STARTWORKTIME:
        	if(alarm.getWorkTimeDate()!=null){
        		hour=alarm.getWorkTimeDate().get(Calendar.HOUR_OF_DAY);
        		minute=alarm.getWorkTimeDate().get(Calendar.MINUTE);
    		}else{
    			//默认1小时之后
    			hour=(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)+1)%24;
    			minute=Calendar.getInstance().get(Calendar.MINUTE);
    		}
        	d = new TimePickerDialog(NewOrModifyAlarmActivity.this,
            		new TimePickerDialog.OnTimeSetListener(){

						@Override
						public void onTimeSet(TimePicker view, int hourOfDay,
								int minute) {
							// TODO Auto-generated method stub
							startWorkTimePreference.setSummary(DreamAlarmDateFormat.formatTime(hourOfDay,minute));
						}},
                    hour,minute,DateFormat.is24HourFormat(NewOrModifyAlarmActivity.this));
            d.setTitle(getResources().getString(R.string.worktime_dialog_title));
        	break;
        default:
            d = super.onCreateDialog(id);
        }

        return d;
    }
	
	@Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
		
        if (preference == timePreference) {
            showDialog(DIALOG_TIMEPICKER_TIME);
        } else if (preference == startWorkTimePreference) {
        	showDialog(DIALOG_TIMEPICKER_STARTWORKTIME);
        } 

        return super.onPreferenceTreeClick(preferenceScreen, preference);
    }
	
	// ----------------------------------------------------------------
	// 处理返回
    
    @Override 
	public boolean onKeyDown(int keyCode, KeyEvent event) { 
	    // BACK key    
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	if(System.currentTimeMillis()-haveCheckedKeyBack.getTimeInMillis()>4*1000){
	    		if(!saveChangeAndReturn()){
	    			if(!workTimeLater){
	    				Toast.makeText(this, R.string.handleframe_toast_havenotime_worktime, Toast.LENGTH_SHORT).show();
	    				workTimeLater=false;
	    			}else{
	    				Toast.makeText(this, R.string.handleframe_toast_havenotime_forreturn, Toast.LENGTH_SHORT).show();
	    			}
	    			haveCheckedKeyBack=Calendar.getInstance();
		    	}
	    	}else{
	    		setResult(RESULT_CANCELED); 
		        this.finish(); 
	    	}
	        
	        return true; 
	    }else { 
	        return super.onKeyDown(keyCode, event); 
	    } 
    }
    
    /**
     * if can save change(inputed time),return to main frame,else return false
     * @return
     */
    private boolean saveChangeAndReturn(){
    	if(saveChange()){
    		Intent i = new Intent();  
            Bundle b = new Bundle();  
            b.putSerializable(Constants.KEY_BETWEEN_ACTIVITY_ALARM, alarm);
            b.putBoolean(Constants.KEY_BETWEEN_ACTIVITY_TURNCHANGED, turnChanged);
            i.putExtras(b);
            this.setResult(RESULT_OK, i);  
            this.finish();  
            return true;
    	}
    	return false;
    }
    
    boolean workTimeLater=false;
    
    /**
     * save the changes
     * @return have input time or not
     */
    private boolean saveChange(){
    	if(isAdd){
    		alarm=new Alarm();
    	}
    	
    	if(timePreference.getSummary()==null || 
    			timePreference.getSummary().equals("")){
    		return false;
    	}else{
    		alarm.setTime(timePreference.getSummary().toString());
    	}
    	
    	if(typePreference.getValue().equals(typePreference.getEntryValues()[0].toString())){
    		alarm.setType(Alarm.TYPE_GETUP);
    		if(startWorkTimePreference.getSummary()==null || 
    				startWorkTimePreference.getSummary().equals("")){
    			return false;
    		}else{
    			alarm.setWorkTime(startWorkTimePreference.getSummary().toString());
        		alarm.setRingSource(ringPreference.getValue());
        		if(alarm.getWorkTimeDate().getTimeInMillis()-alarm.getTimeDate().getTimeInMillis()-14*1000*60<=0){
        			return false;
        		}
        		workTimeLater=true;
        	}
    	}else{
    		alarm.setType(Alarm.TYPE_NOTIFY);
    	}
    	
    	if(turnOnPreference.isChecked()){
    		alarm.setState(Alarm.TURN_ON);
    	}else{
    		alarm.setState(Alarm.TURN_OFF);
    	}
    	if(!isAdd){
    		if(stateInit!=alarm.getState()){
    			turnChanged=true;
    		}
    	}
    	
    	alarm.setRepeat(Integer.parseInt(repeatPreference.getValue()));
    	alarm.setTag(tagPreference.getText());
    	alarm.setEndType(closeMethodPreference.getIntValue());
    	alarm.setReringInterval(intervalLongPreference.getIntValue());
    	
    	return true;
    }
    
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
